package com.lego.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lego.bean.Goods;
import com.lego.bean.Orders;
import com.lego.bean.User;
import com.lego.service.GoodsService;
import com.lego.service.OrdersService;
import com.lego.service.impl.GoodsServiceImpl;
import com.lego.service.impl.OrdersServiceImpl;

@WebServlet("/payment.do")
public class PaymentServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		GoodsService gds = new GoodsServiceImpl();
		OrdersService os = new OrdersServiceImpl();
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
 	   	Object u = session.getAttribute("loginUser");
 	   	//获取登录的用户信息
 	   	User loginUser = null;
 	   	if (u != null) {
 	   		try {
 	            loginUser = (User) u; // 强制类型转换
 	            // 现在可以使用user对象
 	            
 	        } catch (ClassCastException e) {
 	            // 处理类型转换失败的情况
 	            System.err.println("用户未登录");
 	            session.removeAttribute("loginUser"); // 移除无效属性
 	        }
 	    }
		int goodsId = 0;
		int totalQuantity = 0;
		try {
			goodsId = Integer.parseInt(request.getParameter("goodsId"));
		} catch (Exception e) {
			System.out.println("没有查询到该商品信息");
		}
		try {
			totalQuantity = Integer.parseInt(request.getParameter("totalQuantity"));
		} catch (Exception e) {
			System.out.println("没有查询到该商品信息");
		}
		if(totalQuantity==0) {
			response.sendRedirect("purchase.jsp");
		}
		//获取goods相关信息
		Goods goods = gds.selectByGoodsId(goodsId);
		System.out.println("goodsid"+goodsId);
		//生成订单信息，传入数据库
		//生成随机订单号
		int sellerId = goods.getSellerId();
		int userId = 0;
		if(loginUser!=null) {
			userId = loginUser.getUserId();
		}
		double price = goods.getPrice();
		double totalAmount = price*totalQuantity;
		String orderStatus = "pending";
		String orderNumber = null;
		boolean isuuid = false;
		try {
			orderNumber = URLDecoder.decode(request.getParameter("orderNumber"), "UTF-8");
		} catch (Exception e) {
			System.out.println("没有传入订单编号");
			System.out.println("生成了uuid");
			UUID uuid = UUID.randomUUID();
			orderNumber = "#"+uuid.toString();
			isuuid = true;
		}
		System.out.println(orderNumber);
		Orders order = new Orders(orderNumber,sellerId,userId,goodsId,totalQuantity,totalAmount,orderStatus);
		System.out.println(order);
		if(isuuid){
			os.addOrders(order);
		}
		
		//将order信息存入request对象，跳转到payment.jsp
		request.setAttribute("order", order);
		request.setAttribute("goods", goods);
		request.getRequestDispatcher("payment.jsp").forward(request, response);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req,resp);
	}
}
